var controlLocationTypeval;
//控件类型监听
layui.use(['form','layer'], function () {
	
    var form = layui.form,layer = layui.layer;
	form.on('select(locationType)', function(data){
				controlLocationTypeval=data.value;
		    	showOrHideFieldSet(data.value)
		}); 
		    
	form.on('select(appselect)',function(data){
		    	query();
		});
		
	loadData();
	
	
	$(document).click(function(){
	  if( $("#custContextmenu"))
	   $("#custContextmenu").remove();
	
	});
    
	$("#param").on('keydown',function(e){
		if(e.keyCode==13){
			query();
		}
	});
	
	$("#controlName").on("change",function(e){
		var value = $(this).val();
		$("#controlNumber").val("KJ-"+pinyinUtil.getFirstLetter(value));
	});

   $("#savebtn").on('click',function(){save();});
function loadData(){
	$("#objDtl").hide();
	var appId = $("#applist").val();
	var data = {"appId":appId};
	ajaxPost('../obj/loadData',data,
		function(data){
		 if(!data || !data.data.length){
			 bindContextMenuForBlankTree();
		 }else{
			 $("#blankTree").unbind('contextmenu'); 
			 createObjectTree(data.data);
		 }
		
	},function(data){
		layer.alert(data.errorMsg, {
		icon: 5,
		title: "错误"
		});
	});
}


function query(){
	var param = $("#param").val();
	$("#objDtl").hide();
	var appId = $("#applist").val();
	var data = {"appId":appId,"param":param};
	ajaxPost('../obj/query',data,
		function(data){
		 if(!data || !data.data.length){
			 bindContextMenuForBlankTree();
			 $("#tree").jstree(true).settings.core.data =[];
		 }else{
			 $("#blankTree").unbind('contextmenu'); 
			 $("#tree").jstree(true).settings.core.data = data.data;
		 }
		 
		 $("#tree").jstree(true).refresh();
	},function(data){
		layer.alert(data.errorMsg, {
		icon: 5,
		title: "错误"
		});
	});
}

function createObjectTree(data){
	$('#tree').jstree({
		'core' : {
				'data' : data,
				'multiple':false,
				"check_callback" : true
			},
			'plugins':["dnd","wholerow","contextmenu"],
			'contextmenu': {items: customMenu},
			
		});
		
	 $("#tree").on("click.jstree", function (e) {
		   var id = $(e.target).parents('li').attr('id');
		    showObject(id);
	   }).on("loaded.jstree", function (e, data) {
		   openAndShowFirstRoot(e,data);
	    }).on("refresh.jstree",function(e,data){
		   openAndShowFirstRoot(e,data);
	   }).on('move_node.jstree', function(e,data){
		   moveControl(e,data);
		   var inst = data.instance;  
		   inst.deselect_all(true);
		   inst.select_node(data.node);  
		   showObject(data.node.id);
	   })
}


function moveControl(e,data){
	var parentId = data.parent;
	if(parentId == ""||parentId == "#")
		return false;
	var id = data.node.id;
	var oldParentId = data.node.parentId;
	//如果移动的parentId和节点本身的parentId一致，则放弃移动
	if(parentId == oldParentId)
		return false;
	ajaxPost('../obj/changeControlParent',{id:id,parentId:parentId},
			function(data){},
			function(err){
			layer.alert(err.errorMsg,{
				icon:5,
				title:"错误"
			});
		$("#tree").jstree('move_node',data.node,data.old_parent,data.old_position);
	});
}

function openAndShowFirstRoot(e,data){
	  var inst = data.instance;  
	  var data = inst.get_json();
	  if(!data || data.length == 0)
		  return false;
	  var obj = inst.get_node(e.target.firstChild.firstChild.lastChild);  
	  inst.open_all(obj);
	  inst.select_node(obj);  
	  showObject(obj.id);
}

function bindContextMenuForBlankTree(){ 
	 $("#blankTree").contextmenu(function(e){
		 creatRootContextmenu(e);
		 e.preventDefault();
	 });
}


function showOrHideFieldSet(val){
	$("div[id$='-div']").hide();
	if(val == 1)
		$("#objectType-div").show();
	if(val == 2)
		$("#locationType-div").show();
	if(val == 3)
		$("#imgType-div").show();
	if(val == 4)
		$("#areaType-div").show();
}

function creatRootContextmenu(e){
	    $("#custContextmenu").remove();
	    e = e || window.event;
        var left = e.pageX || e.clientX + document.body.scroolLeft;
        var top = e.pageY || e.clientY + document.body.scrollTop;
	   $('<ul id="custContextmenu" class="vakata-context jstree-contextmenu jstree-default-contextmenu" style="left:'+left+'px; top: '+top+'px; display: block;">'+
		 '<li class=""><a href="#" rel="0" onclick="createRoot()"><i></i><span class="vakata-contextmenu-sep">&nbsp;</span>创建一级</a></li>'+
		 '</ul>').appendTo($("body"))
}


function customMenu(node) {
	var items = {
	  createRootItem: { // The "rename" menu item
		 label: "创建一级",
		 action: function () {createRoot();}
		  },
	  createChildItem: { // The "rename" menu item
		   label: "创建子级",
		   action: function (node) {createChild(node);}
		  },
	 deleteItem: { // The "delete" menu item
		   label: "删除",
		   action: function (node) {delNode(node);}
		  },
	 setRootItem:{
		  label:"设置为根节点",
		  action:function(node){setRootNode(node);}
	 }
		 };
	//本来就是根节点，则没有设置根节点菜单
	var parentNodeId = $("#tree").jstree('get_parent',node)
    if(parentNodeId == ""||parentNodeId == "#")
    	delete items.setRootItem;
		 return items;
}


function createRoot(){
     resetTreeValue();
     $("#objDtl").show();
}
	
window.createRoot = createRoot;
function createChild(node){
	resetTreeValue();
	var inst = $.jstree.reference(node.reference),  
    obj = inst.get_node(node.reference); 
	$("#parentId").val(obj.id);
    var parentIds = obj.original.parentIds?(obj.original.parentIds+","+obj.id):obj.id;
    $("#parentIds").val(parentIds);
    $("#parentControlName").val(obj.text)
    $("#objDtl").show();
}


function delNode(node){
	resetTreeValue();
	var inst = $.jstree.reference(node.reference),  
    obj = inst.get_node(node.reference);
	var isLeaf = inst.is_leaf(obj);
	if(!isLeaf){
		layer.confirm("你选择删除的含有子节点，如果继续将删除掉该目录以及其下所有控件，是否继续",
				{btn:['继续','放弃']},
				function(index){deleteControl(obj);layer.close(index);},
				function(index){layer.close(index);});
	}else
		deleteControl(obj);
}



function deleteControl(obj){
	var parentNodeId = $("#tree").jstree('get_parent',$("#"+obj.id));
	ajaxPost('../obj/delObjectNode',{controlId:obj.id},
			function(){
				$("#tree").jstree('delete_node',$("#"+obj.id));
				if(parentNodeId){
					var parentNode = $("#tree").jstree('get_node',parentNodeId);
					$("#tree").jstree('select_node',parentNode);
					showObject(parentNodeId);
				}
	        },
	        function(data){
	        	layer.alert(data.errorMsg, {
	    			icon: 5,
	    			title: "错误"
	    			});
	        });
	
}

function setRootNode(node){
	var inst = $.jstree.reference(node.reference),  
    obj = inst.get_node(node.reference); 
	ajaxPost('../obj/setControlToRoot',{id:obj.id},
			function(data){
				$("#tree").jstree('move_node',obj,"#","last");
			},
			function(data){
				layer.alert(data.errorMsg, {
	    			icon: 5,
	    			title: "错误"
	    			});
			});
}

function showObject(id){
	if(id == ""){
		layer.alert("请选择左边控件树目录", {
			icon: 5,
			title: "错误"
			});
		return false;
	}
	resetTreeValue();
	var parentName = "";
	var parentNodeId = $("#tree").jstree('get_parent',$("#"+id));
	if(parentNodeId)
		parentName = $("#tree").jstree('get_node',parentNodeId).text;
	var data = {"controlId":id};
	ajaxPost('../obj/getObjectNode',data,
			function(data){ initObjectNode(data.data,parentName);},
			function(data){
				layer.alert(data.errorMsg, {
					icon: 5,
					title: "错误"
					});
			});
}

function initObjectNode(data,parentName){
	$("#controlId").val(data.id);
	$("#parentId").val(data.parentId);
	//如果为修改，则取自身的parentIds
	$("#parentIds").val(data.parentIds);
    $("#parentControlName").val(parentName);
	$("#controlName").val(data.controlName);
	$("#controlType").val(data.controlType);
	$("#controlStatus").val(data.controlStatus);
	$("#controlNumber").val(data.controlNumber);
	$("#controlLocationType").val(data.controlLocationType);
	controlLocationTypeval=data.controlLocationType;
	$("#commonType").val(data.commonType);
	$("div[id$='-div']").hide();
	if(data.controlLocationType == 1){
		$("#controlCode").val(data.controlCode);
		$("#objectType-div").show();
	}else if(data.controlLocationType == 2){
		var xy = data.controlXY.split(",");
		$("#location-X").val(xy[0]);
		$("#location-Y").val(xy[1]);
		$("#locationType-div").show();
	}else if(data.controlLocationType == 3){
		$("#controlImg").attr("src","data:image/jpeg;base64,"+data.pictrueBase);
		$("#imgType-div").show();
	}else if(data.controlLocationType == 4){
		var xy = data.controlStartXY.split(",");
		$("#start-X").val(xy[0]);
		$("#start-Y").val(xy[1]);
		$("#width").val(data.controlWidth);
		$("#height").val(data.controlHeight);
		$("#areaType-div").show();
	}
	$("#objDtl").show();
	form.render("select")
}

function save(){
	var data = {};
	var appId = $("#applist").val();
	if(!appId){
		layer.tips("请选择应用","#applist",{
			  tips: [1, '#FF0000'],
			  time: 3000
			});
		return false;
	}
	data["appId"] = appId;
	
	var parentId = $("#parentId").val();
	if(parentId != '')
	data["parentId"] = parentId;
	
	var parentIds = $("#parentIds").val();
	if(parentIds != '')
		data['parentIds'] = parentIds;
	
	var controlName = $("#controlName").val();
	if(controlName == ""){
		layer.tips('请输入控件名称', '#controlName',{
			  tips: [1, '#FF0000'],
			  time: 3000
			});
		return false;
	}
	data["controlName"] = controlName;
	
	var controlType = $("#controlType").val();
	data["controlType"] = controlType;
	
	var controlStatus = $("#controlStatus").val();
	data["controlStatus"] = controlStatus;
	
	var controlNumber = $('#controlNumber').val();
	if(controlNumber == ""){
		layer.tips('请输入控件编码', '#controlNumber',{
			  tips: [1, '#FF0000'],
			  time: 3000
			});
		return false;
	
	}
	var numberPrefix = $("#controlNumber").prev("span").text();
	data["controlNumber"] = numberPrefix+controlNumber;
	
	var controlLocationType = $("#controlLocationType").val();
	data["controlLocationType"] = controlLocationType;
	
	var commonType = $("#commonType").val();
	data["commonType"] = commonType;
	
	
	
	if(controlLocationType == 1){
		var controlCode = $("#controlCode").val();
		data['controlCode'] =controlCode;
	}else if(controlLocationType == 2){
		var x = $("#location-X").val();
		if(x == ""){
			layer.tips("X坐标不能为空","#location-X",{
				  tips: [1, '#FF0000'],
				  time: 3000
				});
			return false;
		}
		var y = $("#location-Y").val();
		if(y == ""){
			layer.tips("Y坐标不能为空","#location-Y",{
				  tips: [1, '#FF0000'],
				  time: 3000
				});
			return false;
		}
		data["controlXY"] = x+","+y;
	}else if(controlLocationType == 3){
		var screenHeight = $("#devicesHeights").val();
		var pictrueBase = $("#controlImg").attr("src").replace("data:image/png;base64,","");
		if(pictrueBase == ""){
			layer.tips("图片信息不能为空","#width",{
				  tips: [1, '#FF0000'],
				  time: 3000
				});
			return false;
		}
		data['pictrueBase']=pictrueBase;
		data['screenHeight']=screenHeight;
		
	}else if(controlLocationType == 4){
		var startX = $("#start-X").val();
		if(startX == ""){
			layer.tips("起始位置X坐标不能为空","#start-X",{
				  tips: [1, '#FF0000'],
				  time: 3000
				});
			return false;
		}
		var startY = $("#start-Y").val();
		if(startY == ""){
			layer.tips("起始位置Y坐标不能为空","#start-Y",{
				  tips: [1, '#FF0000'],
				  time: 3000
				});
			return false;
		}
		
		data["controlStartXY"] = startX+","+startY;
		
		var width = $("#width").val();
		if(width == ""){
			layer.tips("控件区域宽不能为空","#width",{
				  tips: [1, '#FF0000'],
				  time: 3000
				});
			return false;
		}
		
		var height = $("#height").val();
		if(height == ""){
			layer.tips("控件区域高不能为空","#height",{
				  tips: [1, '#FF0000'],
				  time: 3000
				});
			return false;
		}
		
		data["controlWidth"] = width;
		data["controlHeight"] = height;
	}
	
	var id = $("#controlId").val();
	if(id != ""){
		data["id"] = id;
	}
	ajaxPost('../obj/saveNode',data,
			function(data){
			    var parentNode = parentId == ""?"#":$("#"+parentId)
			    var nodeId = "";
				if(id == ""){
					$("#tree").jstree('create_node',parentNode,data.data,"last");
					$("#controlId").val(data.data.id);
					$("#controlNumber").val(data.data.controlNumber);
					nodeId = data.data.id;
				}else{
					var prev =$("#"+id).prevAll();
					//console.log($("#tree").jstree('_previousSibling',$("#"+id)));
					$("#tree").jstree('delete_node',$("#"+id));
					$("#tree").jstree('create_node',parentNode,data.data[0],prev.length);
					nodeId = id;
				}
				$("#tree").jstree("deselect_all",true)
				$("#tree").jstree('select_node',nodeId);
				layer.alert('保存成功',{
					icon:1,
					title:"成功"
				});
			},function(data){
				layer.alert(data.errorMsg, {
					icon: 5,
					title: "错误"
					});
	});
	
}

function resetTreeValue(){
	$("#controlId").val("");
	$("#parentId").val("");
	$("#parentIds").val("");
	$("#parentControlName").val("");
	$("#controlName").val("");
	$("#controlType").val(1);
	$("#controlStatus").val(1);
	$("#controlNumber").val("");
	$("#controlLocationType").val(1);
	controlLocationTypeval=1;
	$("#commonType").val(1);
	$("div[id$='-div']").hide();
	$("#objectType-div").show();
	$("#controlCode").val("");
	$("#location-X").val("");
	$("#location-Y").val("");
	$("#start-X").val("");
	$("#start-Y").val("");
	$("#width").val("");
	$("#height").val("");
	form.render("select");
}
})
